package com.xiaoyi.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;


/**
 * @author xiaoyi
 * @version 1.0.0
 * @date 2023/08/01 16:18:00
 */

public class MD5Util {

    private MD5Util() {
    }

    static {
        // 防止内存中出现多次BouncyCastleProvider的实例
        if (null == Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)) {
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    public static byte[] mdBytes = null;

    /**
      * MD5加密大写
      * @author xiaoyi
      * @version 1.0.0
      * @date 2023/8/1 16:19
      */
    public static String md5Upper32(String data) {
        try {
            mdBytes = MessageDigest.getInstance("MD5").digest(
                    data.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5不存在！");
        }
        String mdCode = new BigInteger(1, mdBytes).toString(16);

        if (mdCode.length() < 32) {
            int a = 32 - mdCode.length();
            for (int i = 0; i < a; i++) {
                mdCode = "0" + mdCode;
            }
        }
        return mdCode.toUpperCase();
    }

     /**
       * MD5加密小写
       * @author xiaoyi
       * @version 1.0.0
       * @date 2023/8/1 16:19
       */
    public static String md5lower32(String data) {
        try {
            mdBytes = MessageDigest.getInstance("MD5").digest(
                    data.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5不存在！");
        }
        String mdCode = new BigInteger(1, mdBytes).toString(16);

        if (mdCode.length() < 32) {
            int a = 32 - mdCode.length();
            for (int i = 0; i < a; i++) {
                mdCode = "0" + mdCode;
            }
        }
        return mdCode;
    }
    /**
     * 生成16位小写的md5加密
     */
    public static String md5lower16(String plainText) {
        String str = md5lower32(plainText);
        return str.substring(8, 24);
    }
    /**
     * 生成16位小写的md5加密
     */
    public static String md5Upper16(String plainText) {
        String str = md5lower32(plainText);
        return str.substring(8, 24);
    }

    public static void main(String[] args) {
        String value = "1234";
        System.out.println(md5lower16(value));
        System.out.println(md5Upper16(value));
    }
}

